package ltd.bugs.cute.channel.selector;

import java.util.List;

import org.springframework.util.CollectionUtils;

import ltd.bugs.cute.channel.model.Channel;

/**
 * 权重选择器，根据权重随机返回其中某个通道
 * 
 * @author zhengzhq
 *
 */
public class WeightSelector implements Selector {

  @Override
  public Channel select(List<Channel> channels) {
    if (CollectionUtils.isEmpty(channels)) {
      return null;
    }

    int totalWeight = 0;
    for (Channel channel : channels) {
      totalWeight += channel.getWeight();
    }

    // 生成一个随机数
    double randomNum = Math.random();
    double num = 0;
    for (Channel channel : channels) {
      num += 1.0 * channel.getWeight() / totalWeight;
      if (num > randomNum) {
        return channel;
      }
    }

    return null;
  }
}
